package com.rockcent.mall.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.Prop;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.QRCodeHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.IntegrationCouponWalletSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 积分卡券管理
 * Created by zhangjh on 2016/12/19.
 */
@RestController
public class IntegrationCouponController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(IntegrationCouponController.class);
    @Autowired
    private MerchantCertifyRepository merchantCertifyRepository;
    @Autowired
    private BaseUserHelper userHelper;
    @Autowired
    private Prop prop;
    @Autowired
    private QRCodeHelper qrCodeHelper;
    @Autowired
    private MerchantCouponRepository merchantCouponRepository;

    @Autowired
    private IntegrationCouponAuditRepository integrationCouponAuditRepository;

    @Autowired
    private IntegrationEventRepository integrationEventRepository;

    @Autowired
    private IntegrationChannelRepository integrationChannelRepository;

    @Autowired
    private CouponMerchantStoreRepository couponMerchantStoreRepository;

    @Autowired
    private IntegrationCouponWalletSrv integrationCouponWalletSrv;


    @Autowired
    private CouponMerchantProductsRepository couponMerchantProductsRepository;

    @Autowired
    private MerchantProductRepository merchantProductRepository;

    @Autowired
    private MerchantStoreRepository merchantStoreRepository;


    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private MerchantOrderItemRepository merchantOrderItemRepository;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private EvaluationRepository evaluationRepository;

    /**
     * @api {get} /mall/integration/coupon/page M端 积分优惠券审核 分页
     * @apiGroup INTEGRATION_COUPON
     * @apiVersion 1.0.0
     * @apiHeader  {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     *
     * @apiParam  {String} name 卡券名称
     * @apiParam  {String} merchantName 商家名称
     * @apiParam  {String} faceValue 抵用面值
     * @apiParam  {String=ALL("全部"), VOUCHERS("抵用券"), DISCOUNT("折扣券")} type <code>参数 </code> 卡券类型
     * @apiParam  {String=WAIT_ISSUE("已审核"), WAIT_AUDIT("待审核")} status <code>必传参数</code> 类型
     * @apiParam  {String=WAIT_ISSUE("全部"), PASS_AUDIT("审核通过"), FAIL_AUDIT("审核不通过"), SOLDOUT("停止发放")} integrationStatus <code>可选参数，在已审核列表为必传参数</code> 状态
     *
     * @apiSuccess {Long} id 卡卷ID
     * @apiSuccess {String = VOUCHERS("抵用券"), DISCOUNT("折扣券")} type 卡卷类型
     * @apiSuccess {String} name 卡券名称
     * @apiSuccess {String} merchantName 商家名称 (点击是调用商家推广二维码接口)
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {BigDecimal} faceValue 抵用面值
     * @apiSuccess {long} quantity 发放总量
     * @apiSuccess {date} dateDisabled 有效期至
     * @apiSuccess {date} auditTime 审核时间
     * @apiSuccess {String} productList 指定产品
     * @apiSuccess {String} storeList 指定门店
     * @apiSuccess {String=WAIT_ISSUE("已审核"), WAIT_AUDIT("待审核")} status 状态
     *
     * @apiSuccessExample {json} Success-Response:
     *{
     *"code": "1",
     *"desc": "成功",
     *"data": {
     *  "data": [
     *      {
     *          "id": 25,
     *          "dateCreated": "2016-06-28 15:08:45",
     *          "lastUpdated": "2016-06-28 15:31:13",
     *          "auditTime": "2016-06-28 15:31:13",
     *          "type": "VOUCHERS",
     *          "name": "expired",
     *          "faceValue": 10,
     *          "quantity": 111,
     *          "dateEnabled": "2016-06-26",
     *          "dateDisabled": "2016-06-26",
     *          "status": "WAIT_ISSUE",
     *          "merchantId": 1,
     *          "merchantName": "超五",
     *          "productList": "32",
     *     }
     *     .......
     *  ]
     *}
     *}
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_COUPON_PAGE, method = RequestMethod.GET)
    public JsonResult integrationCouponPage (HttpServletRequest request, MerchantCouponDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getStatus()) || !EnumUtils.isValidEnum(MerchantCouponStatus.class, dto.getStatus())) {
                jsonResult.remind("status 参数错误, 必须为 WAIT_ISSUE(\"已审核\"), WAIT_AUDIT(\"待审核\")",log);
                return;
            }
            if (StringUtils.isBlank(dto.getType()) || !EnumUtils.isValidEnum(CouponType.class, dto.getType())) {
                jsonResult.remind("type 参数错误，必须为  ALL(\"全部\"), VOUCHERS(\"抵用券\"), DISCOUNT(\"折扣券\")",log);
                return;
            }
            PageResult<MerchantCouponDto> pageResult = merchantCouponRepository.findIntegrationCouponPage(userInfoDto.mall.getId(), dto.getName(), dto.getMerchantName(), dto.getFaceValue(), dto.getStatus(), dto.getIntegrationStatus(), dto.getType(),this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.data.stream().map(merchantCoupon ->{
//                List<MerchantCouponProducts> merchantCouponProductsList = couponProductsRepository.findByCouponId(merchantCoupon.getId());
//                if (merchantCouponProductsList.size() > 0) {
//                    merchantCoupon.setProductCount(merchantCouponProductsList.size());
//                }
//                List<CouponMerchantStore> storeList = couponMerchantStoreRepository.findByCouponId(merchantCoupon.getId());
//                if (storeList.size() > 0) {
//                    merchantCoupon.setStoreCount(storeList.size());
//                }

                if (merchantCoupon.getUseScope().equals(CouponUseScope.PART_STORE.toString()) ) {
                    List<CouponMerchantStore> storeList = this.couponMerchantStoreRepository.findByCouponIdAndIsDelete(merchantCoupon.getId(), Whether.NO);
                    StringBuilder storeIds = new StringBuilder();
                    for (int i = 0; i < storeList.size(); i++) {
                        CouponMerchantStore store = storeList.get(i);
                        if (i < storeList.size() - 1) {
                            storeIds.append(store.getStoreId() + ",");
                        } else {
                            storeIds.append(store.getStoreId());
                        }
                    }
                    merchantCoupon.setStoreList(storeIds.toString());
                    merchantCoupon.setCouponStoreCount(new Long(storeList.size()));
                }
                else if (merchantCoupon.getUseScope().equals(CouponUseScope.PART_PRODUCT.toString())) {
                    List<CouponMerchantProducts> productsList = this.couponMerchantProductsRepository.findByCouponIdAndIsDelete(merchantCoupon.getId(), Whether.NO);
                    StringBuilder productIds = new StringBuilder();
                    for (int i = 0; i < productsList.size(); i++) {
                        CouponMerchantProducts product = productsList.get(i);
                        if (i < productsList.size() - 1) {
                            productIds.append(product.getProductId() + ",");
                        } else {
                            productIds.append(product.getProductId());
                        }
                    }
                    merchantCoupon.setProductList(productIds.toString());
                    merchantCoupon.setCouponProductCount(new Long(productsList.size()));
                }
                return merchantCoupon;
            }).collect(Collectors.toList());
            pageResult.setUrl(Routes.MALL_INTEGRATION_COUPON_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /mall/integration/coupon/audit M端 积分优惠券审核 审核
     * @apiGroup INTEGRATION_COUPON
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id 卡券ID
     * @apiParam {String} remark 审核备注
     * @apiParam {String} status <code>PASS_AUDIT(审核通过) FAIL_AUDIT(审核不通过)</code>审核状态
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_INTEGRATION_COUPON_AUDIT, method = RequestMethod.POST)
    public JsonResult integrationCouponAudit (HttpServletRequest request, @RequestBody MerchantCouponDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long couponId = dto.getId();
            if (couponId == null) {
                jsonResult.remind(MerchantCoupon.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }


            String dtoStatus = dto.getStatus();
            if (StringUtils.isBlank(dtoStatus) || !EnumUtils.isValidEnum(IntegrationEventType.class, dtoStatus)) {
                jsonResult.remind("审核状态只允许 PASS_AUDIT(审核通过) FAIL_AUDIT(审核不通过)",log);
                return;
            }

            if(IntegrationEventType.valueOf(dtoStatus)==IntegrationEventType.FAIL_AUDIT){
                if (StringUtils.isBlank(dto.getRemark())) {
                    jsonResult.remind("审核备注 不能为空",log);
                    return;
                }
            }

            MerchantCoupon coupon = merchantCouponRepository.findOne(couponId);
            if (coupon == null) {
                jsonResult.remind("积分卡券不存在",log);
                return;
            }

            if (coupon.getIntegration() == Whether.NO) {
                jsonResult.remind("此卡卷不是积分优惠券",log);
                return;
            }
            if (coupon.getStatus() != MerchantCouponStatus.WAIT_AUDIT) {
                jsonResult.remind("待审核的卡券才能审批",log);
                return;
            }
            Long couponMerchantId = coupon.getMerchantId();
            IntegrationCouponAudit integrationCouponAudit = integrationCouponAuditRepository.findByCouponIdAndMerchantIdAndIsDelete(couponId, couponMerchantId, Whether.NO);
            if (integrationCouponAudit == null) {
                jsonResult.remind("审核记录不存在",log);
                return;
            }

            integrationCouponAudit.setRemark(dto.getRemark());
            IntegrationEvent integrationEvent = new IntegrationEvent();

            SysMessage message = null;
            if (IntegrationEventType.PASS_AUDIT == IntegrationEventType.valueOf(dtoStatus)) {
                if (IntegrationEventType.PASS_AUDIT == integrationCouponAudit.getStatus()) {
                    jsonResult.remind("已审核通过的卡券不能再审核",log);
                    return;
                }
                integrationEvent.setEventType(IntegrationEventType.PASS_AUDIT);
                integrationCouponAudit.setStatus(IntegrationEventType.PASS_AUDIT);
                coupon.setStatus(MerchantCouponStatus.WAIT_ISSUE);
                String frontendUrl =SysMessageConstants.M2B_INTEGRATION_COUPON_AUDIT_PASS.getFrontendUrl();
                frontendUrl = MessageFormat.format(frontendUrl,couponId);
                SysMessageConstants.M2B_INTEGRATION_COUPON_AUDIT_PASS.setFrontendUrl(frontendUrl);
                String content = SysMessageConstants.M2B_INTEGRATION_COUPON_AUDIT_PASS.getContent();
                content = MessageFormat.format(content, coupon.getName());
                message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_INTEGRATION_COUPON_AUDIT_PASS, SysMessageType.OP, content);

            }
            if (IntegrationEventType.FAIL_AUDIT == IntegrationEventType.valueOf(dtoStatus)) {
                integrationEvent.setEventType(IntegrationEventType.PASS_AUDIT);
                integrationCouponAudit.setStatus(IntegrationEventType.FAIL_AUDIT);
                coupon.setStatus(MerchantCouponStatus.UNAUDITED);

                String frontendUrl =SysMessageConstants.M2B_INTEGRATION_COUPON_AUDIT_UNPASS.getFrontendUrl();
                frontendUrl = MessageFormat.format(frontendUrl,couponId);
                SysMessageConstants.M2B_INTEGRATION_COUPON_AUDIT_UNPASS.setFrontendUrl(frontendUrl);
                String content = SysMessageConstants.M2B_INTEGRATION_COUPON_AUDIT_UNPASS.getContent();
                content = MessageFormat.format(content, coupon.getName(),dto.getRemark());
                message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_INTEGRATION_COUPON_AUDIT_UNPASS, SysMessageType.SYS, content);

            }

            Long anUserInfoDtomallId = coupon.getMallId();
            integrationEvent.setMallId(anUserInfoDtomallId);
            String anUserInfoDtomerchantName = userInfoDto.getUsername();
            integrationEvent.setOperator(anUserInfoDtomerchantName);
            integrationEvent.setMerchantId(couponMerchantId);
            integrationEvent.setOperatorId(userInfoDto.getId());
            integrationEvent.setCouponId(couponId);
            integrationEventRepository.save(integrationEvent);
            integrationCouponAuditRepository.save(integrationCouponAudit);
            coupon = merchantCouponRepository.save(coupon);
            if (IntegrationEventType.PASS_AUDIT == IntegrationEventType.valueOf(dtoStatus)) {

                integrationCouponWalletSrv.batchSave(coupon);

                dto.setChannelId(1l);
                dto.setChannelName("广发证券");
                MerchantCoupon merchantCoupon = merchantCouponRepository.findByIdAndMallId(couponId, anUserInfoDtomallId);
                if (merchantCoupon == null) {
                    jsonResult.remind(MerchantCoupon.REMIND_RECORD_IS_NOT_EXIST,log);;
                    return;
                }
                putChannel(dto, userInfoDto, merchantCoupon);
            }

            //广播消息
            SysMessageHelper.SINGLETON.pushMsgByMallAndMerchantId(message, null, couponMerchantId);

        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /mall/integration/coupon/launches M端 积分优惠券审核 投放渠道
     * @apiGroup INTEGRATION_COUPON
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id 卡卷ID
     * @apiParam {Long} channelId 渠道ID
     * @apiParam {String} channelName 渠道名称
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_INTEGRATION_COUPON_LAUNCHES, method = RequestMethod.PUT)
    public JsonResult integrationCouponLaunches (HttpServletRequest request, @RequestBody MerchantCouponDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MerchantCoupon.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }

            if (dto.getChannelId() == null) {
                jsonResult.remind("渠道ID 不能为空",log);
                return;
            }

//            if (StringUtils.isBlank(dto.getChannelName())) {
//                jsonResult.remind("渠道名称 不能为空",log);
//                return;
//            }

            IntegrationChannel integrationChannel = integrationChannelRepository.findByIdAndMallIdAndIsDelete(dto.getChannelId(), userInfoDto.mall.getId(), Whether.NO);
            if (integrationChannel == null) {
                jsonResult.remind("渠道不存在",log);
                return;
            }

            MerchantCoupon merchantCoupon = merchantCouponRepository.findByIdAndMallId(dto.getId(), userInfoDto.mall.getId());
            if (merchantCoupon == null) {
                jsonResult.remind(MerchantCoupon.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }

            putChannel(dto, userInfoDto, merchantCoupon);
        };
        return doing.go(request, log);
    }

    private void putChannel(@RequestBody MerchantCouponDto dto, UserInfoDto userInfoDto, MerchantCoupon merchantCoupon) {
        merchantCoupon.setStatus(MerchantCouponStatus.ISSUED);
        merchantCoupon.setIntegrationChannelId(dto.getChannelId());

        Long  merchantCouponId  = merchantCoupon.getId();
        Long integrationChannelId  = dto.getChannelId();
        Long mallId = userInfoDto.mall.getId();
        Long maxBatchPutNo = merchantCouponRepository.queryMaxBatchPutNo(mallId,integrationChannelId);
        Long nexBatchPutNo = maxBatchPutNo+1;
        merchantCoupon.setBatchPutNo(nexBatchPutNo);
        merchantCouponRepository.save(merchantCoupon);

        IntegrationEvent integrationEvent = new IntegrationEvent();
        integrationEvent.setEventType(IntegrationEventType.CHANNEL_LAUNCHES);
        integrationEvent.setMallId(merchantCoupon.getMallId());
        integrationEvent.setMerchantId(merchantCoupon.getMerchantId());
        integrationEvent.setOperator(userInfoDto.getUsername());
        integrationEvent.setOperatorId(userInfoDto.getId());
        integrationEvent.setCouponId(merchantCoupon.getId());
        integrationEventRepository.save(integrationEvent);

        // 设置 intergration_coupon_wallet 的渠道ID
        //integrationCouponWalletRepository.saveChannelIdByCouponId(merchantCoupon.getId(), dto.getChannelId(), userInfoDto.mall.getId());


        integrationCouponWalletSrv.updateIntegrationChannelId(merchantCouponId,integrationChannelId, mallId, nexBatchPutNo, merchantCoupon.getMerchantName());
    }

    /**
     * @api {put} /mall/integration/coupon/stop M端 积分优惠券审核 停止发放
     * @apiGroup INTEGRATION_COUPON
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id 卡卷ID
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_INTEGRATION_COUPON_STOP, method = RequestMethod.PUT)
    public JsonResult integrationCouponStop (HttpServletRequest request, @RequestBody MerchantCouponDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MerchantCoupon.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            Long mallI = userInfoDto.mall.getId();
            MerchantCoupon merchantCoupon = merchantCouponRepository.findByIdAndMallId(dto.getId(), mallI);
            if (merchantCoupon == null) {
                jsonResult.remind(MerchantCoupon.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            merchantCoupon.setStatus(MerchantCouponStatus.SOLDOUT);
            merchantCouponRepository.save(merchantCoupon);

            IntegrationEvent integrationEvent = new IntegrationEvent();
            integrationEvent.setEventType(IntegrationEventType.STOP_LAUNCHES);
            integrationEvent.setMallId(mallI);
            integrationEvent.setMerchantId(merchantCoupon.getMerchantId());
            integrationEvent.setOperator(userInfoDto.getUsername());
            integrationEvent.setOperatorId(userInfoDto.getId());
            Long merchantCouponId = merchantCoupon.getId();
            integrationEvent.setCouponId(merchantCouponId);
            integrationEventRepository.save(integrationEvent);

            //intergration_coupon_wallet 失效
//            integrationCouponWalletRepository.deleteByCouponId(merchantCouponId, mallI);

            integrationCouponWalletSrv.stop(merchantCouponId, mallI);
        };
        return doing.go(request, log);
    }



    /**
     * @api {get}  /mall/coupon/useage B端  查看卡券适用门店|产品信息
     * @apiGroup mall_coupon
     * @apiVersion 1.0.0
     * @apiHeader  {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam  {Long} id 卡券ID
     * @apiParam {String} productList: <code>格式[1,2,3,4]</code> 适用产品ID集合
     * @apiParam {String} storeList: <code>格式[1,2,3,4]</code> 适用门店ID集合
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     *  "data": {
     *      "id": 125,
     *      "promoteUrl": "http://uploads.rockcent.com/dev/coupon/promote/201611/8144041195ba45c141-1613-4bdc-ba46-4a3345a0f3e3giftPacketPromote.jpg",
     *      "sendOutUrl": "http://beta.c.dev.rockcent.com/mall.php?method=detail&couponId=125&salesCode=B@AfvahtT"
     *      }
     *  }
     */
    @RequestMapping(value = Routes.MALL_COUPON_USEAGE, method = RequestMethod.GET)
    public JsonResult showCouponUseAge(MerchantCouponDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            if (dto.getId() == null) {
                jsonResult.remind("卡券ID 不能为空", log);
                return;
            }

            MerchantCoupon coupon = this.merchantCouponRepository.findOne(dto.getId());
            if(null!=coupon){
                CouponUseScope useScope = coupon.getUseScope();
                if (useScope == CouponUseScope.PART_STORE) {

                    List<Long> storeIdList = RequestUtils.string2list(objectMapper, dto.getStoreList());
                    if (storeIdList == null || storeIdList.isEmpty()) {
                        jsonResult.remind("加载门店列表失败",log);
                        return;
                    }
                    List<MerchantStore> storeList = merchantStoreRepository.findByStatusAndExchangeAndIdIn(MerchantStoreStatus.ENABLE, Whether.YES, storeIdList);
                    jsonResult.data = storeList;
                }
                else if (useScope == CouponUseScope.PART_PRODUCT) {
                    List<Long> proList = RequestUtils.string2list(objectMapper, dto.getProductList());
                    if (proList == null || proList.isEmpty()) {
                        jsonResult.remind("加载产品列表失败",log);
                        return;
                    }
                    List<ProductDto> productList = merchantProductRepository.findAllByIds( proList);
                    productList.stream().map(product -> {
                        Double goodRate  = evaluationRepository.queryGoodRateByProductId(product.getId());
                        String goodRates = goodRate ==null?"0":String.valueOf(goodRate);
                        log.info("======================>goodRates:"+goodRates);
                        product.setGoodRate(goodRates);
                        return product;
                    }).collect(Collectors.toList());
                    jsonResult.data = productList;
                }
            }

        };

        return doing.go(request, log);
    }



    /**
     *
     * @api {put} /mall/send/out M端 商户管理 推广
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiSuccessExample {json} Success-Response:
     *{
     *"code": "1",
     *"desc": "成功",
     *"data": {
     *   "promoteUrl": "http://uploads.rockcent.com/dev/coupon/promote/201611/8144438785f0d66d37-682d-424f-a9c2-5bf3c270d4c7giftPacketPromote.jpg",
     *   "sendOutUrl": "http://beta.c.dev.rockcent.com/mall.php?method=detail&couponId=133&salesCode=B@AfvahtT"
     *  }
     *}
     **/
    @RequestMapping(value = Routes.MALL_SEND_OUT, method = RequestMethod.PUT)
    public JsonResult sendOutMerchant(@RequestBody MerchantCouponDto dto,HttpServletRequest request) {

        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if (mall == null) {
                jsonResult.remind("平台不存在,请联系开发人员",log);
                return;
            }
            Merchant merchant = merchantRepository.findOne(dto.getMerchantId());
            String host = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(host)) {
                host = mall.getMobileHostName();
            }
            StringBuffer url = new StringBuffer();
            //推广链接，待定
            url.append("http://").append(host).append("/wechat/merchant/" + merchant.getId()).append("/?id=").append(merchant.getId());


            QrCodeDto qrCodeDto = new QrCodeDto();
            qrCodeDto.setId(userInfoDto.getId());
            qrCodeDto.setMallId(userInfoDto.mall.getId());
            qrCodeDto.setMerchantId(dto.getMerchantId());
            UploadImageFileDto uploadImageFileDto = qrCodeHelper.createQRCode(qrCodeDto, url.toString(), "merchantSendOutQR.jpg", UploadFileBusinessType.MERCHANT_PROMOTE, prop.env, prop.aliyunOssBucketName, prop.domainUploadsHttp);
            merchant.setPromoteUrl(uploadImageFileDto.getPath());
            merchantRepository.save(merchant);
            MerchantDto merchantDto = new MerchantDto();
            merchantDto.setSendOutUrl(url.toString());
            merchantDto.setPromoteUrl(merchant.getPromoteUrl());
            jsonResult.data = merchantDto;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /coupon/merchant/info 商户 信息
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam  {Long} id 卡券ID
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     *      "id": 1,
     *      "name": "商户名称",
     *      "telNo": "138001380000",
     *      "saleProductCount": 78000,
     *      "saleTotalAmout": 12000000.00,
     *      "saleOrderAmount": 89000,
     *      "visitorCount": 90876600
     *      }
     * }
     */
    @RequestMapping(value = Routes.COUPON_MERCHANT_INFO, method = RequestMethod.GET)
    public JsonResult info(Long id,HttpServletRequest request) {

        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            MerchantCoupon coupon = this.merchantCouponRepository.findOne(id);
            if (coupon == null) {
                jsonResult.remind("没有相应卡券信息",log);
                return;
            }
            Long merchantId = coupon.getMerchantId();
            coupon.getMallId();
            Merchant merchant = merchantRepository.findOne(merchantId);
            log.info("======================>merchant:"+merchant);
            if (merchant == null) {
                jsonResult.remind("没有相应商户信息",log);
                return;
            }

            CouponMerchantDto couponMerchantDto  = new CouponMerchantDto();
            MerchantCertify merchantCertify = merchantCertifyRepository.findByMerchantIdAndMallId(merchantId,  coupon.getMallId());
            log.info("======================>merchantCertify:"+merchantCertify);
            String name =merchant.getName();
            String telNo = merchantCertify.getContactPhone();
            Long saleProductCount =  merchantOrderItemRepository.countSaleProductCountByMerchantId(merchantId);
            Double saleTotalAmout=  merchantOrderItemRepository.countSaleTotalAmoutByMerchantId(merchantId);
            Long saleOrderAmount = merchantOrderItemRepository.countSaleOrderAmountByMerchantId(merchantId);
//            String visitorCount;


            couponMerchantDto.setName(name);
            couponMerchantDto.setTelNo(telNo);
            couponMerchantDto.setSaleProductCount(saleProductCount);
            couponMerchantDto.setSaleTotalAmout(saleTotalAmout);
            couponMerchantDto.setSaleOrderAmount(saleOrderAmount);



            jsonResult.data = couponMerchantDto;

        };
        return doing.go(request, log);
    }
}
